<template>
  <div class="basic-from">
    <div class="card-box">
      <div class="card-title">基本信息</div>
      <el-form :model="formData" size="small" ref="form" class="form-wrap" :rules="rules">
        <el-form-item label="报销编号" prop="reimbursementCode" v-if="isEdit">
          <el-input v-halfCharCode v-model="formData.reimbursementCode" readonly />
        </el-form-item>
        <el-form-item label="报销名称" prop="reimbursementName">
          <el-input v-halfCharCode type="input" placeholder="请输入报销名称，内容最长为64个字符" v-model="formData.reimbursementName" maxlength="64" />
        </el-form-item>
        <el-form-item label="报销类型" prop="reimbursementType">
          <el-select clearable v-model="formData.reimbursementType" value-key="label" filterable :filter-method="dataFilter">
            <el-option v-for="item in optionss" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请部门" prop="unitName">
          <br />
          <el-input v-halfCharCode type="input" placeholder="请输入报销名称，内容最长为64个字符" disabled v-model="formData.unitName" maxlength="64" />
        </el-form-item>
        <el-form-item label="申请人" prop="applyPerson">
          <el-input v-halfCharCode type="input" v-model="formData.applyPerson" placeholder="请输入申请人，内容最长为64个字符" maxlength="64" />
        </el-form-item>

        <el-form-item label="申请时间" prop="applyStartTime">
          <el-date-picker type="date" v-model="formData.applyStartTime" placeholder="申请时间" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>

        <el-form-item label="审批模板" prop="approveTemplate">
          <el-select clearable v-model="formData.approveTemplate" value-key="label" filterable :filter-method="dataFilter" @change="clearPrintData()">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <section ref="printTemplate" id="printTemplate">
        <!-- 将报销编号reimId传给子组件rid-->
        <approve-form ref="approveForm" v-if="formData.approveTemplate=='0'" @commit="commit()" :printData="printData" />
        <payment-approve-form ref="paymentApproveForm" v-else-if="formData.approveTemplate=='1'" @commit="commit()" :printData="printData" />
        <fund-supervision-payment-form
          ref="fundSupervisionPaymentForm"
          v-else-if="formData.approveTemplate=='2'"
          @commit="commit()"
          :printData="printData"
        />
      </section>
    </div>
    <div class="cFormFoot">
      <el-button type="primary" @click="submit" class="printButton">打印并提交</el-button>
    </div>
  </div>
</template>

<script>
import { getDictAndPlease } from "~/utils";
import { mapState } from "vuex";
import printJS from "print-js";

import {
  getObj,
  addObj,
  putObj,
  getNewId
} from "@/views/wy-reimbursement/api/reimbursement";
import approveForm from "~/views/wy-reimbursement/components/approve-form";
import paymentApproveForm from "~/views/wy-reimbursement/components/payment-approve-form";
import fundSupervisionPaymentForm from "~/views/wy-reimbursement/components/fund-supervision-payment-form";

export default {
  components: {
    approveForm: approveForm,
    paymentApproveForm: paymentApproveForm,
    fundSupervisionPaymentForm: fundSupervisionPaymentForm
  },
  mounted () {
    this.remoteQuery();
    //qh+:获取URL上的参数
    this.formData.reimbursementId = this.$route.query.id;
    if (this.formData.reimbursementId) {
      this.queryItem();
      this.isEdit = true
    } else {
      getNewId().then(response => {
        this.formData.reimbursementId = response.data.msg;
        this.formData.unitName = this.user.deptName;
      });
    }
    // this.getTest()
  },
  data () {
    return {
      isEdit: false,
      tableData: [],
      formData: {
        unitName: "",
        reimbursementId: "",
        reimbursementType: "",
        applyStartTime: "",
        applyPerson: "",
        approveTemplate: "",
        approveTemplateId: ""
      },
      //通过查询得到打印表的数据。
      printData: {},
      printDataCopy: {},
      approveTemplateCopy: "",
      newReimbursementId: "",
      rules: {
        unitName: [
          {
            required: true,
            message: "单位名称不能为空",
            trigger: "blur"
          }
        ],
        reimbursementId: [
          {
            required: true,
            message: "报销编号不能为空",
            trigger: "blur"
          }
        ],
        reimbursementType: [
          {
            required: true,
            message: "报销类型不能为空",
            trigger: "blur"
          }
        ],
        reimbursementName: [
          {
            required: true,
            message: "报销名称不能为空",
            trigger: "blur"
          }
        ],
        applyStartTime: [
          {
            required: true,
            message: "请选择申请时间",
            trigger: "change"
          }
        ],
        applyPerson: [
          {
            required: true,
            message: "申请人不能为空",
            trigger: "blur"
          }
        ],
        approveTemplate: [
          {
            required: true,
            message: "请选择审批模板",
            trigger: "change"
          }
        ]
      },
      //报销类型的字典值
      options: [],
      optionss: [],
      optionsCopy: [],
      value: ""
    };
  },
  computed: {
    ...mapState({
      user: state => state.user.user,
      approve_template: state => {
        let data =
          state.dict.find(item => item.type === "approve_template") ||
          {};
        let list = data.children || [];
        return data.children || [];
      }
    })
  },
  methods: {
    getTest () {
      // console.log(this.approve_template)
    },
    remoteQuery () {
      this.options = getDictAndPlease("approve_template");
      this.optionss = getDictAndPlease("reimbursement_type");
      this.optionsCopy = this.options;
      // console.log(this.options)
    },
    prints () {
      printJS({
        printable: "printTemplate",
        type: "html",
        frameId: "printFrame",
        //properties: [
        //    { field: 'name', displayName: '姓名', columnSize:`50%`},
        //    { field: 'sex', displayName: '性别',columnSize:`50%`},
        //],
        // header: `<p class="custom-p"> 名单 </p>`,
        style: this.getPrintStyle(),
        // gridHeaderStyle:'font-size:12px; padding:3px; border:1px solid; font-weight: 100; text-align:left;',
        // gridStyle:'font-size:12px; padding:3px; border:1px solid; text-align:left;',
        // repeatTableHeader: true,
        scanStyles: false, //扫描页面样式
        // scanStyles:false,  //使用自定义页面样式
        targetStyles: ["*"]
      });
      this.$nextTick(function () {
        this.closeNowRouter();
      });
      // this.remove_ie_header_and_footer();
      // this.$Print(this.$refs.printTemplate)
    },
    submit () {
      if (this.formData.approveTemplate == "0") {
        this.$refs.approveForm.check();
      } else if (this.formData.approveTemplate == "1") {
        this.$refs.paymentApproveForm.check();
      } else if (this.formData.approveTemplate == "2") {
        this.$refs.fundSupervisionPaymentForm.check();
      } else {
        this.commit();
      }
    },
    commit () {
      let approveTemplateForms = this.printData;
      this.formData.approveTemplateForms = approveTemplateForms;
      this.formData.approveTemplateForms.approveType = this.formData.approveTemplate;
      // JSON.parse(JSON.stringify(this.formData))
      //
      let reimbursementVO = JSON.parse(JSON.stringify(this.formData));

      this.$refs.form.validate(valid => {
        if (valid) {
          //验证通过执行打印提交
          if (
            reimbursementVO.approveTemplateForms
              .approveTemplateId == undefined ||
            reimbursementVO.approveTemplateForms
              .approveTemplateId == null ||
            reimbursementVO.approveTemplateForms.approveTemplateId.trim() ==
            ""
          ) {
            addObj(reimbursementVO).then(response => {
              if (response.data.data) {
                this.suc("提交成功");
                this.prints();
              }
            });
          } else {
            putObj(reimbursementVO).then(response => {
              if (response.data.data) {
                this.suc("提交成功");
                this.prints();
              }
            });
          }
        }
      });
    },
    // 去除页眉/页脚
    remove_ie_header_and_footer () {
      var hkey_path;
      hkey_path =
        "HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
      try {
        var RegWsh = new ActiveXObject("WScript.Shell");
        RegWsh.RegWrite(hkey_path + "header", "");
        RegWsh.RegWrite(hkey_path + "footer", "");
      } catch (e) { }
    },
    dataFilter (val) {
      this.formData.approveTemplate = val;
      if (val) {
        //val存在
        this.options = this.optionsCopy.filter(item => {
          if (
            !!~item.label.indexOf(val) ||
            !!~item.label.toUpperCase().indexOf(val.toUpperCase())
          ) {
            return true;
          }
        });
      } else {
        //val为空时，还原数组
        this.options = this.optionsCopy;
      }
    },
    queryItem () {
      //查询单条报销记录
      getObj(this.formData.reimbursementId).then(respdata => {
        this.formData = respdata.data.data;
        //查询出来的approveTemplate为整形，而下拉列表为字符，转化
        this.formData.approveTemplate = this.formData.approveTemplateForms.approveType;
        this.printData = respdata.data.data.approveTemplateForms;
        this.printDataCopy = this.printData;
        this.approveTemplateCopy = this.formData.approveTemplate;
        console.log(this.printData, "printData");
      });
    },
    getPrintStyle () {
      const commonStyle = `

                .approve-form-table{
                    align-content: center;
                    vertical-align: center;
                    text-align: center;
                    box-sizing:border-box;
                    /*border: solid #bfbfbf 1px;*/
                }

                table{
                    border: solid #bfbfbf 1px;
                    border-collapse: collapse;
                    max-width: 100%;
                    font-weight:normal;
                    font-family: Avenir,Helvetica,Arial,sans-serif;
                    font-size:12px;
                }
                tr{
                    height: 50px;
                }
                .table-input{
                    width: 90%;
                    float: left;

                }
                input,textarea{
                border: none;box-shadow: none;width: 100%; overflow:hidden; resize:none; line-height: 1.76em;
                }
                td{
                    font-size: 10pt;
                }
            `;
      switch (this.formData.approveTemplate) {
        case "0":
          return (
            commonStyle +
            `
                        .template-head{
                            text-align: center;
                            align-content: center;
                            width: 100%;
                            margin-top: 10px;
                        }

                        td{
                            border: solid #bfbfbf 1px;
                            padding: 20px 10px !important;
                            text-align:center;
                        }
                        td:nth-child(3){
                            height: 100px;
                        }

                        .table-div{
                            width: 96%;
                            align-content: center;
                            margin: 10px auto;
                        }

                        .template-head-font{
                            font-size: 30px;
                            color: #999999;
                            width: 88%;
                        }

                        .head-time{
                            vertical-align: center;
                            font-size: 14px;
                            float: right;
                            margin-right: 2%;
                        }
                    `
          );
        case "1":
          return (
            commonStyle +
            `
                    .template-head{
                        text-align: center;
                        align-content: center;
                        width: 100%;
                        margin-top: 10px;
                        margin-left: 2%;
                    }
                    td{
                        border: solid #bfbfbf 1px;
                        padding: 10px 20px;
                    }

                    .table-div{
                        width: 96%;
                        align-content: center;
                        margin: 30px auto;
                    }

                    .template-head-font{
                    font-size: 30px;
										color: #999999;
										width: 88%;
                    }

                    .head-time{
                        font-size: 14px;
                        float: right;
                        margin-right: 4%;
                    }
                    `
          );
        case "2":
          return (
            commonStyle +
            `
                    .template-head{
                      	text-align: center;
                        align-content: center;
                        width: 100%;
                        margin-top: 10px;
                        margin-left: 2%;
                    }

                    td{
                        border: solid #bfbfbf 1px;
                        padding: 10px 20px;
                    }

                    .table-div{
                        width: 96%;
                        align-content: center;
                        margin: 30px auto;
                    }

                    .template-head-font{
                      font-size: 30px;
  										color: #999999;
 											width: 88%;
                    }

                    .head-time{
                        font-size: 14px;
                        float: right;
                        margin-right: 4%;
                    }
                    `
          );
        default:
          break;
      }
    },
    closeNowRouter () {
      this.$router.back();
    },
    clearPrintData () {
      if (this.formData.approveTemplate === this.approveTemplateCopy) {
        this.printData = this.printDataCopy;
      } else {
        this.printData = {};
        this.printData.approveTemplateId = this.printDataCopy.approveTemplateId;
      }
    }
  }
};
</script>

<style scoped lang='scss'>
.labelFont {
  font-size: 14px;
  color: #999999;
}
.card-box {
  overflow: hidden;
  margin: 24px;
  .printButton {
    float: right;
  }
}
@media print {
  .card-box {
    margin-left: -80px;
    width: 95%;
    /*text-align: center;*/
    margin-bottom: 14mm;
    border-bottom: 0;
  }

  .card-box td {
    color: #f00;
  }
}

@page {
  size: auto A4 landscape;
  /*size: auto;*/
  margin: 3mm;
}
</style>
